<template>
  <el-card class="music-center-card">
    <el-row :gutter="30" class="music-center-layout">
      <el-col :span="10" class="player-main-col">
        <div class="album-art-container">
          <img 
            :src="musicStore.currentSong?.albumArt || 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png'" 
            class="album-art"
            :class="{'is-playing': musicStore.isPlaying}"
          >
        </div>
        <div class="song-details">
          <h3 class="song-title">{{ musicStore.currentSong?.name || '未选择歌曲' }}</h3>
          <p class="song-artist">{{ musicStore.currentSong?.artist || '请从右侧选择或搜索歌曲' }}</p>
        </div>
        <div class="progress-controls">
          <span class="time-label">{{ formatTime(musicStore.currentTime) }}</span>
          <el-slider 
            v-model="musicStore.currentTime" 
            :max="musicStore.duration" 
            :show-tooltip="false"
            @change="handleSliderChange"
            class="progress-slider"
          />
          <span class="time-label">{{ formatTime(musicStore.duration) }}</span>
        </div>
        <div class="player-buttons">
          <el-button :icon="DArrowLeft" @click="musicStore.prevSong" circle size="large" />
          <el-button 
            :icon="musicStore.isPlaying ? VideoPause : VideoPlay" 
            @click="musicStore.togglePlayPause" 
            circle 
            size="large"
            type="primary"
            class="play-pause-btn"
          />
          <el-button :icon="DArrowRight" @click="musicStore.nextSong" circle size="large" />
        </div>
      </el-col>

      <el-col :span="14" class="playlist-col">
        <el-autocomplete
          v-model="searchKeyword"
          :fetch-suggestions="handleSearch"
          placeholder="搜索歌曲或歌手..."
          @select="handleSelect"
          style="width: 100%; margin-bottom: 20px;"
          size="large"
        >
          <template #default="{ item }">
            <div class="suggestion-item">
              <span>{{ item.name }}</span>
              <span class="artist">{{ item.artist }}</span>
            </div>
          </template>
        </el-autocomplete>
        
        <el-tabs value="playlist" class="playlist-tabs">
          <el-tab-pane label="当前播放列表" name="playlist">
            <div class="table-container">
              <el-table :data="musicStore.playlist" stripe style="width: 100%" height="100%" @row-dblclick="handleRowClick" :row-class-name="tableRowClassName">
                <el-table-column type="index" width="50" label="序号" />
                <el-table-column prop="name" label="歌曲">
                   <template #default="{ row }">
                    <div class="song-cell">
                      <span>{{ row.name }}</span>
                      <el-tag v-if="row.fee === 1" type="warning" size="small" effect="dark" class="vip-tag">VIP</el-tag>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="artist" label="歌手" />
              </el-table>
            </div>
             <el-empty v-if="!musicStore.playlist.length" description="播放列表为空" />
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useMusicStore } from '../../stores/musicStore';
import musicService from '../../services/musicService';
import { VideoPlay, VideoPause, DArrowLeft, DArrowRight } from '@element-plus/icons-vue';

const musicStore = useMusicStore();
const searchKeyword = ref('');

onMounted(() => {
  if (musicStore.playlist.length === 0) {
    musicStore.loadPlaylist('3778678');
  }
});

const handleSearch = async (queryString, cb) => {
  if (!queryString) return cb([]);
  const songs = await musicService.searchMusic(queryString);
  const results = songs.map(song => ({
    ...song,
    value: song.name,
    artist: song.ar.map(a => a.name).join(' / '),
  }));
  cb(results);
};

const handleSelect = (item) => {
  musicStore.playSongFromSearch(item);
  searchKeyword.value = '';
};

const handleRowClick = (row) => {
  const index = musicStore.playlist.findIndex(song => song.id === row.id);
  if (index !== -1) {
    musicStore.playSong(index);
  }
};

const handleSliderChange = (value) => {
  musicStore.updateCurrentTime(value);
};

const formatTime = (time) => {
  if (isNaN(time) || time === 0) return '00:00';
  const minutes = Math.floor(time / 60);
  const seconds = Math.floor(time % 60);
  return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
};

const tableRowClassName = ({ row }) => {
  if (musicStore.currentSong && row.id === musicStore.currentSong.id) {
    return 'current-song-row';
  }
  return '';
};
</script>

<style scoped>
.music-center-card {
  height: calc(100vh - 124px);
  min-height: 600px;
}
:deep(.el-card__body) {
  height: 100%;
}
.music-center-layout {
  height: 100%;
}
.player-main-col {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  border-right: 1px solid var(--vt-c-border-color-light);
}
.album-art-container {
  width: 65%;
  max-width: 300px;
  aspect-ratio: 1 / 1;
  margin-bottom: 30px;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 10px 40px rgba(0,0,0,0.15);
}
.album-art {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.album-art.is-playing {
  animation: spin 20s linear infinite;
}
@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
.song-details {
  text-align: center;
  margin-bottom: 20px;
}
.song-title {
  font-size: 22px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: var(--vt-c-text-1);
}
.song-artist {
  font-size: 16px;
  color: var(--vt-c-text-2);
  margin: 0;
}
.progress-controls {
  width: 100%;
  max-width: 400px;
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
}
.time-label {
  font-size: 12px;
  color: #909399;
  width: 40px;
  text-align: center;
}
.player-buttons {
  display: flex;
  align-items: center;
  gap: 20px;
}
.play-pause-btn {
  transform: scale(1.3);
}
.playlist-col {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.playlist-tabs {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}
:deep(.el-tabs__content) {
  flex-grow: 1;
  height: 0;
}
:deep(.el-tab-pane) {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.table-container {
  flex-grow: 1;
  height: 0; /* Important for flexbox to correctly calculate height */
}
.suggestion-item .artist {
  margin-left: 10px;
  font-size: 0.9em;
  color: #999;
}
.song-cell {
  display: flex;
  align-items: center;
}
.vip-tag {
  margin-left: 8px;
  transform: scale(0.9);
}
:deep(.el-table .current-song-row) {
  background-color: var(--el-color-primary-light-9) !important;
  color: var(--el-color-primary) !important;
  font-weight: bold;
}
</style>